# -*- coding: utf-8 -*-
'''
 Source file
 File name: alias.py
 Creation date: 13-09-2011
 Modification date : 29-12-2011
 Author: dassier
 Last modifier : itey
 Release: 
    -> Modification on -l option if alias section is not defined
    -> Add option verbose
'''

from svi.command.basecmd import *
import getopt
import sys
import re
from ConfigParser import *


class command(BaseCmd):
    ''' Alias management
        alias allows to reduce url syntaxe, by defining short text to represent full url (example: test-main -> http://www.example.com/svn/test/dev/main)
    '''

    def __init__(self, param, client, conf):
        ''' param: list of arguement
            client: svn client object
            conf: Config object
        '''
        # Call base class initialisation
        super(command, self).__init__(param, client, conf)

    def help(self):
        self._msg.banner()
        self._msg.help(u'"alias" command inline help')
        self._msg.help(u'''Syntaxe: svi alias [-v] -d <name> | -l | -a <alias name> <URL>
                -a <name> <url>: Create a new alias named <name> for <url>
                -l:              List all defined alias
                -d <name>:       Delete alias <name> from alias list
                -v:              Verbose for debug
                       ''')

    def run(self):
        ''' Execute command, and raise error if any
        '''
        # Parse arguement
        try:
            opts, arg_list = getopt.getopt(self._param, 'd:a:l')
        except getopt.GetoptError, err:
            # print error message
            self._msg.error(err)
            self.help()
            sys.exit(2)

        # Only one option can be set
        if len(opts) != 1:
            self.help()
            raise CommandLineError(u"Option (-a, -d or -l) cannot be used together")
        o, a = opts[0]
        if o == "-l":
            # List all alias
            # Get alias from conf
            if not self._conf.has_section("alias"):
                # section alias is not defined
                self._msg.error("Alias not defined")
            else:
                # section alias is defined
                self._msg.info(u"Liste of available alias:\n")
                for alias in self._conf.options("alias"):
                    self._msg.info(u'"//%s"  ==>  "%s"' % (alias, self._conf.get("alias", alias)))
        elif o == "-a":
            # Add new alias
            # Create alias section if not exists
            if not self._conf.has_section("alias"):
                self._conf.add_section("alias")
            # Now arguement of 'a' option is alias name
            # and last argument of param is url name
            if arg_list == []:
                # Last arguement missing
                self.help()
                raise CommandLineError(u"URL is missing")
            # Test if alias already exists
            if self._conf.has_option("alias", a):
                # Alias already present, cannot create one
                raise ParameterError(u'Alias "%s" already present in configuration' % a)
            else:
                # Create new alias
                # suppress '//' at begining of alias if defined
                a = a.lstrip("/")
                self._conf.set("alias", a, arg_list[0])
                self._msg.ok(u'Alias "//%s" [%s] defined' % (a, arg_list[0]))
        elif o == "-d":
            # Delete alias
            # First test if section or alias presents in configuration
            if not self._conf.has_section("alias"):
                s.elf._msg.error("Alias not defined")
            else:
                # Delete alias
                if self._conf.remove_option("alias", a):
                    # Success
                    self._msg.ok(u'Alias "%s" removed' % a)
                else:
                    # Alias not defined
                    self._msg.error(u'Alias "%s" not defined' % a)

        self._conf.save()

class ReplaceAlias:
    ''' Replace alias by the real URL if defined in configuration
    '''

    def __init__(self, conf):
        ''' Parameter: conf: Config object
        '''
        self._conf = conf

    def replace(self, name):
        ''' Search if name contains an alias
            If an alias is found, replace it by the corresponding url
        '''
        # extract alias from name
        # search for alias pattern: name must begin with '//'
        match_obj = re.match('^//(\w+)/?', name)
        if match_obj is None:
            # No alias found, return 'name' parameter unchanged
            return name
        alias = match_obj.group(1)
        # Search option in conf.
        try:
            repl_alias = self._conf.get("alias", alias)
        except (NoOptionError, NoSectionError):
            # alias not defined
            return name
        # Replace  alias by its full name and return
        alias = "//%s" % alias
        return re.sub(alias, repl_alias, name)


